<template>
  <view class="container" v-bind:style="appThemeStyle">
    <mescroll-body ref="mescrollRef\" :sticky="true" @init="mescrollInit" :down="{ native: true }" @down="downCallback" :up="upOption"
      @up="upCallback">
      <!-- 页面头部 -->
      <view class="header">
        <view class="search">
          <search :tips="options.search ? options.search : '搜索商品'" @event="handleSearch" />
        </view>
        <!-- 切换列表显示方式 -->
        <view class="show-view" @click="handleShowView">
          <text class="iconfont icon-view-tile" v-if="showView"></text>
          <text class="iconfont icon-view-list" v-else></text>
        </view>
      </view>
      <!-- 排序标签 -->
      <view class="store-sort">
        <view class="sort-item" :class="{ active: sortType === 'all' }" @click="handleSortType('all')">
          <text>综合</text>
        </view>
        <view class="sort-item" :class="{ active: sortType === 'sales' }" @click="handleSortType('sales')">
          <text>销量</text>
        </view>
        <view class="sort-item sort-item-price" :class="{ active: sortType === 'price' }" @click="handleSortType('price')">
          <text>价格</text>
          <view class="price-arrow">
            <view class="icon up" :class="{ active: sortType === 'price' && !sortPrice }">
              <text class="iconfont icon-arrow-up"></text>
            </view>
            <view class="icon down" :class="{ active: sortType === 'price' && sortPrice }">
              <text class="iconfont icon-arrow-down"></text>
            </view>
          </view>
        </view>
        <!-- 筛选按钮 -->
        <view class="sort-item" :class="{ active: showFilterPanel }" @click="toggleFilterPanel">
          <text>筛选</text>
          <text class="iconfont icon-filter" style="margin-left: 6rpx; font-size: 24rpx;"></text>
        </view>
      </view>
      <!-- 商品列表 -->
      <view class="goods-list clearfix" :class="['column-' + (showView ? '1' : '2')]">
        <view class="goods-item" v-for="(item, index) in list.data" :key="index" @click="onTargetDetail(item.goods_id)">
          <!-- 单列显示 -->
          <view v-if="showView" class="dis-flex">
            <!-- 商品图片 -->
            <view class="goods-item-left">
              <image class="image" :src="item.goods_image"></image>
            </view>
            <view class="goods-item-right">
              <!-- 商品名称 -->
              <view class="goods-name">
                <text class="twoline-hide">{{ item.goods_name }}</text>
              </view>
              <view class="goods-item-desc">
                <!-- 商品卖点 -->
                <view class="desc-selling-point dis-flex">
                  <text class="oneline-hide">{{ item.selling_point }}</text>
                </view>
                <!-- 商品销量 -->
                <view class="desc-goods-sales dis-flex">
                  <text>已售{{ item.goods_sales }}件</text>
                </view>
                <!-- 商品价格 -->
                <view class="desc-footer">
                  <text class="price-x">¥{{ item.goods_price_min }}</text>
                  <text class="price-y col-9" v-if="item.line_price_min > 0">¥{{ item.line_price_min }}</text>
                </view>
              </view>
            </view>
          </view>
          <!-- 多列显示 -->
          <view v-else class="">
            <!-- 商品图片 -->
            <view class="goods-image">
              <image class="image" mode="aspectFill" :src="item.goods_image"></image>
            </view>
            <view class="detail">
              <!-- 商品名称 -->
              <view class="goods-name">
                <text class="twoline-hide">{{ item.goods_name }}</text>
              </view>
              <!-- 商品价格 -->
              <view class="detail-price oneline-hide">
                <text class="goods-price f-30 col-m">￥{{ item.goods_price_min }}</text>
                <text v-if="item.line_price_min > 0" class="line-price col-9 f-24">￥{{ item.line_price_min }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </mescroll-body>

    <!-- 筛选面板遮罩 -->
    <view class="filter-panel-mask" v-if="showFilterPanel" @click="closeFilterPanel"></view>
    
    <!-- 筛选面板 -->
    <view class="filter-panel" :class="{ 'filter-panel-show': showFilterPanel }">
      <view class="filter-panel-container">
        <!-- 左侧分类标签 -->
        <view class="filter-tabs">
          <view 
            v-for="(tab, index) in filterTabs" 
            :key="index" 
            class="filter-tab-item" 
            :class="{ active: currentFilterTab === index }"
            @click="switchFilterTab(index)"
          >
            {{ tab.title }}
          </view>
        </view>
        
        <!-- 右侧筛选内容 -->
        <view class="filter-content">
          <scroll-view scroll-y class="filter-scroll-view">
            <!-- 服务/折扣 -->
            <view v-if="currentFilterTab === 0" class="filter-options-container">
              <view class="filter-options">
                <view 
                  v-for="(option, index) in filterTabs[0].options" 
                  :key="index"
                  class="filter-option" 
                  :class="{ active: tempSelectedFilters.includes(option) }"
                  @click="toggleFilter(option)"
                >
                  {{ option }}
                </view>
              </view>
            </view>
            
            <!-- 价格区间 -->
            <view v-if="currentFilterTab === 1" class="filter-options-container">
              <view class="filter-options">
                <view 
                  v-for="(option, index) in filterTabs[1].options" 
                  :key="index"
                  class="filter-option" 
                  :class="{ active: tempSelectedFilters.includes(option) }"
                  @click="toggleFilter(option)"
                >
                  {{ option }}
                </view>
              </view>
            </view>
            
            <!-- 品牌 -->
            <view v-if="currentFilterTab === 2" class="filter-options-container">
              <view class="filter-options">
                <view 
                  v-for="(option, index) in filterTabs[2].options" 
                  :key="index"
                  class="filter-option" 
                  :class="{ active: tempSelectedFilters.includes(option) }"
                  @click="toggleFilter(option)"
                >
                  {{ option }}
                </view>
              </view>
            </view>
            
            <!-- 全部分类 -->
            <view v-if="currentFilterTab === 3" class="filter-options-container">
              <view class="filter-options">
                <view 
                  v-for="(option, index) in filterTabs[3].options" 
                  :key="index"
                  class="filter-option" 
                  :class="{ active: tempSelectedFilters.includes(option) }"
                  @click="toggleFilter(option)"
                >
                  {{ option }}
                </view>
              </view>
            </view>
            
            <!-- 按摩手法 -->
            <view v-if="currentFilterTab === 4" class="filter-options-container">
              <view class="filter-options">
                <view 
                  v-for="(option, index) in filterTabs[4].options" 
                  :key="index"
                  class="filter-option" 
                  :class="{ active: tempSelectedFilters.includes(option) }"
                  @click="toggleFilter(option)"
                >
                  {{ option }}
                </view>
              </view>
            </view>
            
            <!-- 功能 -->
            <view v-if="currentFilterTab === 5" class="filter-options-container">
              <view class="filter-options">
                <view 
                  v-for="(option, index) in filterTabs[5].options" 
                  :key="index"
                  class="filter-option" 
                  :class="{ active: tempSelectedFilters.includes(option) }"
                  @click="toggleFilter(option)"
                >
                  {{ option }}
                </view>
              </view>
            </view>
            
            <!-- 适用人群 -->
            <view v-if="currentFilterTab === 6" class="filter-options-container">
              <view class="filter-options">
                <view 
                  v-for="(option, index) in filterTabs[6].options" 
                  :key="index"
                  class="filter-option" 
                  :class="{ active: tempSelectedFilters.includes(option) }"
                  @click="toggleFilter(option)"
                >
                  {{ option }}
                </view>
              </view>
            </view>
            
            <!-- 适用场景 -->
            <view v-if="currentFilterTab === 7" class="filter-options-container">
              <view class="filter-options">
                <view 
                  v-for="(option, index) in filterTabs[7].options" 
                  :key="index"
                  class="filter-option" 
                  :class="{ active: tempSelectedFilters.includes(option) }"
                  @click="toggleFilter(option)"
                >
                  {{ option }}
                </view>
              </view>
            </view>
            
            <!-- 类型 -->
            <view v-if="currentFilterTab === 8" class="filter-options-container">
              <view class="filter-options">
                <view 
                  v-for="(option, index) in filterTabs[8].options" 
                  :key="index"
                  class="filter-option" 
                  :class="{ active: tempSelectedFilters.includes(option) }"
                  @click="toggleFilter(option)"
                >
                  {{ option }}
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
      
      <!-- 底部按钮 -->
      <view class="filter-panel-footer">
        <view class="filter-btn reset-btn" @click="resetFilters">重置</view>
        <view class="filter-btn confirm-btn" @click="applyFilters">
          确定 <text v-if="tempSelectedFilters.length">({{ tempSelectedFilters.length }}+件商品)</text>
          <text v-else>(1400+件商品)</text>
        </view>
      </view>
    </view>
    
    <!-- 仅看有货按钮 -->
    <view class="only-in-stock" v-if="!showFilterPanel">
      <view class="only-in-stock-btn" @click="toggleOnlyInStock">仅看有货</view>
    </view>
  </view>
</template>

<script>
  import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
  import * as GoodsApi from '@/api/goods'
  import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
  import Search from '@/components/search'

  const pageSize = 15
  const showViewKey = 'GoodsList-ShowView';

  export default {
    components: {
      Search
    },
    mixins: [MescrollMixin],
    data() {
      return {
        showView: false, // 列表显示方式 (true列表、false平铺)
        sortType: 'all', // 排序类型
        sortPrice: false, // 价格排序 (true高到低 false低到高)
        options: {}, // 当前页面参数
        list: getEmptyPaginateObj(), // 商品列表数据
        
        // 筛选相关数据
        showFilterPanel: false, // 是否显示筛选面板
        selectedFilters: [], // 已选筛选项
        tempSelectedFilters: [], // 临时存储筛选选项
        currentFilterTab: 0, // 当前选中的筛选标签
        onlyInStock: false, // 仅看有货
        
        // 筛选标签数据
        filterTabs: [
          // {
          //   title: '服务/折扣',
          //   options: ['京东物流', '国家补贴', '211限时达', '同城速配', '百亿补贴', '新品', '分期免息', '包邮', '支持礼品卡', 'PLUS95折', '全球购', '促销', '价保', '配送全球', '货到付款']
          // },
          {
            title: '价格区间',
            options: ['0-100', '100-300', '300-500', '500-1000', '1000-3000', '3000以上']
          },
          // {
          //   title: '品牌',
          //   options: ['飞利浦', '松下', '小米', '华为', '苹果', '三星', 'OPPO', 'vivo', '索尼', '博朗']
          // },
          // {
          //   title: '全部分类',
          //   options: ['按摩器材', '眼部按摩', '颈部按摩', '腰部按摩', '腿部按摩', '足部按摩', '全身按摩']
          // },
          // {
          //   title: '按摩手法',
          //   options: ['揉捏', '推拿', '刮痧', '针灸', '拔罐', '热敷', '震动', '气压']
          // },
          // {
          //   title: '功能',
          //   options: ['缓解疲劳', '改善睡眠', '促进血液循环', '减轻压力', '舒缓肌肉', '美容', '减肥']
          // },
          // {
          //   title: '适用人群',
          //   options: ['老人', '青年', '中年', '儿童', '男士', '女士', '孕妇', '学生']
          // },
          // {
          //   title: '适用场景',
          //   options: ['家用', '办公室', '车载', '旅行', '运动后', '睡前']
          // },
          // {
          //   title: '类型',
          //   options: ['电动', '手动', '充电', '电池', '插电', '无线']
          // }
        ],
        
        // 上拉加载的配置项
        upOption: {
          auto: true, // 是否在初始化完毕之后自动执行上拉加载的回调
          page: {
            num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
            size: pageSize // 每页数据的数量
          },
          noMoreSize: 0, // 配置列表的总数量要大于等于5条才显示无更多数据
          empty: {
            tip: '暂无相关商品~' // 提示
          }
        }
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      // 记录options
      this.options = options
      // 设置默认列表显示方式
      this.setShowView()
    },

    methods: {

      /**
       * 上拉加载的回调 (页面初始化时也会执行一次)
       * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
       * @param {Object} page
       */
      upCallback(page) {
        const app = this
        // 设置列表数据
        app.getGoodsList(page.num)
          .then(list => {
            const curPageLen = list.data.length
            const totalSize = list.data.total
            app.mescroll.endBySize(curPageLen, totalSize)
          })
          .catch(() => app.mescroll.endErr())
      },

      // 设置默认列表显示方式
      setShowView() {
        this.showView = uni.getStorageSync(showViewKey) || false
      },

      /**
       * 获取商品列表
       * @param {number} pageNo 页码
       */
      getGoodsList(pageNo = 1) {
        const app = this
        console.log(app.options)
        const param = {
          sortType: app.sortType,
          sortPrice: Number(app.sortPrice),
          categoryId: app.options.categoryId || 0,
          goodsName: app.options.search || '',
          page: pageNo,
          // 筛选参数
          filters: app.selectedFilters,
          onlyInStock: app.onlyInStock
        }
        return new Promise((resolve, reject) => {
          GoodsApi.list(param)
            .then(result => {
              // 合并新数据
              const newList = result.data.list
              app.list.data = getMoreListData(newList, app.list, pageNo)
              resolve(newList)
            })
            .catch(reject)
        })
      },

      // 切换排序方式
      handleSortType(newSortType) {
        const app = this
        const newSortPrice = newSortType === 'price' ? !app.sortPrice : true
        app.sortType = newSortType
        app.sortPrice = newSortPrice
        // 刷新列表数据
        app.list = getEmptyPaginateObj()
        app.mescroll.resetUpScroll()
      },

      // 切换列表显示方式
      handleShowView() {
        const app = this
        app.showView = !app.showView
        uni.setStorageSync(showViewKey, app.showView)
      },

      // 跳转商品详情页
      onTargetDetail(goodsId) {
        this.$navTo('pages/goods/detail', { goodsId })
      },

      /**
       * 商品搜索
       */
      handleSearch() {
        const searchPageUrl = 'pages/search/index'
        // 判断来源页面
        let pages = getCurrentPages()
        if (pages.length > 1 &&
          pages[pages.length - 2].route === searchPageUrl) {
          uni.navigateBack()
          return
        }
        // 跳转到商品搜索页
        this.$navTo(searchPageUrl)
      },
      
      // 筛选相关方法
      
      // 切换筛选面板显示
      toggleFilterPanel() {
        if (!this.showFilterPanel) {
          // 打开筛选面板时，将已选筛选项复制到临时变量
          this.tempSelectedFilters = [...this.selectedFilters]
        }
        this.showFilterPanel = !this.showFilterPanel
      },
      
      // 关闭筛选面板
      closeFilterPanel() {
        this.showFilterPanel = false
        // 关闭时不应用筛选，恢复之前的选择
        this.tempSelectedFilters = [...this.selectedFilters]
      },
      
      // 切换筛选标签
      switchFilterTab(index) {
        this.currentFilterTab = index
      },
      
      // 切换筛选选项
      toggleFilter(filter) {
        const index = this.tempSelectedFilters.indexOf(filter)
        if (index > -1) {
          this.tempSelectedFilters.splice(index, 1)
        } else {
          this.tempSelectedFilters.push(filter)
        }
      },
      
      // 重置筛选
      resetFilters() {
        this.tempSelectedFilters = []
      },
      
      // 应用筛选
      applyFilters() {
        this.selectedFilters = [...this.tempSelectedFilters]
        this.showFilterPanel = false
        
        // 刷新列表数据
        this.list = getEmptyPaginateObj()
        this.mescroll.resetUpScroll()
      },
      
      // 切换仅看有货
      toggleOnlyInStock() {
        this.onlyInStock = !this.onlyInStock
        
        // 刷新列表数据
        this.list = getEmptyPaginateObj()
        this.mescroll.resetUpScroll()
      },

      /**
       * 设置分享内容
       */
      onShareAppMessage() {
        // 构建分享参数
        const app = this
        return {
          title: "商品列表",
          path: "/pages/goods/list?" + this.$getShareUrlParams(app.options)
        }
      },

      /**
       * 分享到朋友圈
       * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
       * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
       */
      onShareTimeline() {
        // 构建分享参数
        const app = this
        return {
          title: "商品列表",
          path: "/pages/goods/list?" + this.$getShareUrlParams(app.options)
        }
      }

    }
  }
</script>

<style lang="scss" scoped>
  // 页面头部
  .header {
    display: flex;
    align-items: center;
    background-color: #fff;

    // 搜索框
    .search {
      flex: 1;
    }

    // 切换显示方式
    .show-view {
      width: 60rpx;
      height: 60rpx;
      font-size: 36rpx;
      color: #505050;
      display: flex;
      align-items: center;
    }
  }

  // 排序组件
  .store-sort {
    position: sticky;
    top: var(--window-top);
    display: flex;
    padding: 20rpx 0;
    font-size: 28rpx;
    background: #fff;
    color: #000;
    z-index: 99;

    .sort-item {
      flex-basis: 25%; // 修改为4个等分
      display: flex;
      justify-content: center;
      align-items: center;
      height: 50rpx;

      &.active {
        color: $main-bg;
      }
    }

    .sort-item-price .price-arrow {
      margin-left: 20rpx;
      font-size: 24rpx;
      color: #000;

      .icon {
        &.active {
          color: $main-bg;
        }

        &.up {
          margin-bottom: -16rpx;
        }

        &.down {
          margin-top: -16rpx;
        }
      }
    }
  }

  // 商品列表
  .goods-list {
    padding: 4rpx;
    box-sizing: border-box;
  }

  // 单列显示
  .goods-list.column-1 {
    .goods-item {
      width: 100%;
      height: 280rpx;
      margin-bottom: 12rpx;
      padding: 20rpx;
      box-sizing: border-box;
      background: #fff;
      line-height: 1.6;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .goods-item-left {
      display: flex;
      width: 300rpx;
      background: #fff;
      align-items: center;

      .image {
        display: block;
        width: 240rpx;
        height: 240rpx;
      }
    }

    .goods-item-right {
      position: relative;
      flex: 1;

      .goods-name {
        margin-top: 10rpx;
        white-space: normal;
        color: #484848;
        font-size: 26rpx;
        min-height: 68rpx;
        line-height: 1.3;
      }
    }

    .goods-item-desc {
      margin-top: 8rpx;
    }

    .desc-selling-point {
      width: 400rpx;
      font-size: 24rpx;
      color: #e49a3d;
    }

    .desc-goods-sales {
      color: #999;
      font-size: 24rpx;
    }

    .desc-footer {
      font-size: 24rpx;

      .price-x {
        margin-right: 16rpx;
        color: $main-bg;
        font-size: 30rpx;
      }

      .price-y {
        text-decoration: line-through;
      }
    }
  }

  // 平铺显示
  .goods-list.column-2 {
    .goods-item {
      width: 50%;
    }
  }

  .goods-item {
    float: left;
    box-sizing: border-box;
    padding: 6rpx;

    .goods-image {
      position: relative;
      width: 100%;
      height: 0;
      padding-bottom: 100%;
      overflow: hidden;
      background: #fff;

      &:after {
        content: '';
        display: block;
        margin-top: 100%;
      }

      .image {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        -o-object-fit: cover;
        object-fit: cover;
      }
    }

    .detail {
      padding: 8rpx;
      background: #fff;

      .goods-name {
        white-space: normal;
        color: #484848;
        font-size: 26rpx;
        margin-bottom: 4rpx;
        min-height: 68rpx;
        line-height: 1.3;
      }

      .detail-price {
        .goods-price {
          margin-right: 8rpx;
        }

        .line-price {
          text-decoration: line-through;
        }
      }
    }
  }
  
  // 筛选面板相关样式
  .filter-panel-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 999;
  }
  
  .filter-panel {
    position: fixed;
    left: 0;
    right: 0;
    bottom: -100%;
    height: 60vh; /* 设置为视口高度的60% */
    background-color: #fff;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    transition: all 0.3s;
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
  }
  
  .filter-panel-show {
    bottom: 0;
  }
  
  .filter-panel-container {
    flex: 1;
    display: flex;
    overflow: hidden;
  }
  
  .filter-tabs {
    width: 25%;
    height: 100%;
    background-color: #f5f5f5;
    overflow-y: auto;
  }
  
  .filter-tab-item {
    padding: 30rpx 20rpx;
    font-size: 26rpx;
    text-align: center;
    position: relative;
    color: #333;
    
    &.active {
      background-color: #fff;
      color: #333;
      font-weight: bold;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 30rpx;
        background-color: $main-bg;
      }
    }
  }
  
  .filter-content {
    flex: 1;
    height: 100%;
    padding: 20rpx;
    box-sizing: border-box;
  }
  
  .filter-scroll-view {
    height: 100%;
  }
  
  .filter-options-container {
    padding-bottom: 30rpx;
  }
  
  .filter-options {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
  }
  
  .filter-option {
    padding: 15rpx 25rpx;
    border: 1px solid #eee;
    border-radius: 8rpx;
    font-size: 26rpx;
    color: #333;
    
    &.active {
      color: $main-bg;
      border-color: $main-bg;
      background-color: rgba($main-bg, 0.05);
    }
  }
  
  .filter-panel-footer {
    display: flex;
    height: 100rpx;
    border-top: 1px solid #eee;
  }
  
  .filter-btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
  }
  
  .reset-btn {
    background-color: #fff;
    color: #333;
  }
  
  .confirm-btn {
    background-color: $main-bg;
    color: #fff;
  }
  
  // 仅看有货按钮
  .only-in-stock {
    position: fixed;
    bottom: 30rpx;
    right: 30rpx;
    z-index: 90;
  }
  
  .only-in-stock-btn {
    background-color: rgba(255, 255, 255, 0.9);
    color: #333;
    font-size: 26rp;
    padding: 15rpx 30rpx;
    border-radius: 100rpx;
    box-shadow:  0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    border: 1rpx solid #eee;
  }
</style>
